package com.gmstu.springorm.framework;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author John.zhang
 * @version Id: PropertyMapping, v 1.0 2020/9/2 17:19 ZhiYong Exp $
 */
@Slf4j
public class PropertyMapping {

    final Method getter;

    final Method setter;

    final String fieldName;

    final Class enumClass;

    public PropertyMapping(Method getter, Method setter, Field field) {
        this.getter = getter;
        this.setter = setter;
        this.fieldName = field.getName();
        this.enumClass = getter.getReturnType().isEnum() ? getter.getReturnType() : null;
    }

    public void set(Object target, Object value) {
        if (null != enumClass && null != value) {
            value = Enum.valueOf(enumClass, (String) value);
        }
        if (null != value) {
            try {
                setter.invoke(target, setter.getParameterTypes()[0].cast(value));
            } catch (Exception e) {
                e.printStackTrace();
                log.error(fieldName + "--" + value);
            }
        }
    }
}
